package com.kgc.springboot_shiro.realm;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.kgc.springboot_shiro.entity.Role;
import com.kgc.springboot_shiro.entity.User;
import com.kgc.springboot_shiro.entity.UserRole;
import com.kgc.springboot_shiro.mapper.RoleMapper;
import com.kgc.springboot_shiro.mapper.UserRoleMapper;
import com.kgc.springboot_shiro.service.UserRoleService;
import com.kgc.springboot_shiro.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.stream.Collectors;


@Slf4j
public class CustomerRealm  extends AuthorizingRealm {
    @Autowired
    private UserService userService;
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private RoleMapper roleMapper;

    // 授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();

        //获取用户信息
        String primaryPrincipal = (String) principals.getPrimaryPrincipal();

        //根据用户信息查询用户的角色信息
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.eq(User::getUsername,primaryPrincipal);
        User user = userService.getOne(userLambdaQueryWrapper);
        long id = user.getId();
        //根据用户id查询用户角色id
        LambdaQueryWrapper<UserRole> userRoleLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userRoleLambdaQueryWrapper.eq(UserRole::getUserId,id);
        List<UserRole> userRoles = userRoleMapper.selectList(userRoleLambdaQueryWrapper);
        List<Integer> collect = userRoles.stream().map(userRole -> {
            return userRole.getRoleId();
        }).collect(Collectors.toList());
        //根据角色id查询角色


        LambdaQueryWrapper<Role> roleLambdaQueryWrapper = new LambdaQueryWrapper<>();
        roleLambdaQueryWrapper.in(Role::getRoleId,collect);
        List<Role> roles = roleMapper.selectList(roleLambdaQueryWrapper);
        List<String> roleNames = roles.stream().map(role -> {
            return role.getRole();
        }).collect(Collectors.toList());

        simpleAuthorizationInfo.addRoles(roleNames);

        return simpleAuthorizationInfo;
    }

    // 认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        log.info("==========AuthenticationToken============");
        UsernamePasswordToken usernamePasswordToken= (UsernamePasswordToken) token;
        String username = usernamePasswordToken.getUsername();
        System.out.println("username = " + username);
        String principal = (String) token.getPrincipal();
        System.out.println("principal = " + principal);

//        UserService userService = (UserService) ApplicationContextUtils.getBean("userService");
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.isNotEmpty(principal),User::getUsername,principal);
        User user = userService.getOne(wrapper);

        System.out.println("getName"+this.getName());

        System.out.println("user = " + user);
        if (!ObjectUtils.isEmpty(user))
        {
            SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(
                    user.getUsername(),
                    user.getPassword(),
                    ByteSource.Util.bytes(user.getSalt()),
                    this.getName());
            return simpleAuthenticationInfo;
        }
        return null;
    }
}
